<script setup>
  import { ref, reactive } from 'vue'
  import { useRouter } from 'vue-router'
  // 获取生命周期
  import { onLoad } from '@dcloudio/uni-app'
  import userApi from '@/apis/user'
  import { useUserStore } from '@/stores/user'

  const router = useRouter()
  const userStore = useUserStore()
  // 定义获取表单元素的变量
  const accountForm = ref()
  const redirectURL = ref('')
  const routeType = ref('')
  const formData = reactive({
    account: '',
    password: '',
  })
  // 定义验证规则
  const accountRules = reactive({
    account: {
      rules: [
        { required: true, errorMessage: '请输入登录账号' },
        { pattern: /^[a-zA-Z0-9]{6,8}$/, errorMessage: '登录账号格式不正确' },
      ],
    },
    password: {
      rules: [
        { required: true, errorMessage: '请输入登录密码' },
        { pattern: '^\\d{6}$', errorMessage: '登陆密码格式不正确' },
      ],
    },
  })
  // 获取地址中的参数
  onLoad((query) => {
    redirectURL.value = query.redirectURL || '/pages/task/index'
    routeType.value = query.routeType || 'reLaunch'
  })
  // 提交表单数据
  async function onSubmitForm() {
    // 对表单的数据进行验证
    try {
      const fromData = await accountForm.value.validate()
      const { code, data } = await userApi.login(formData)
      // 在pinia中允许直接对数据(state)进行修改
      userStore.token = data
      // #ifdef H5
      router.push({
        path: redirectURL.value,
      })
      // #endif
      // #ifndef H5
      uni[routeType.value]({
        url: redirectURL.value,
      })
      // #endif
    } catch (e) {
      console.log(e)
    }
  }
</script>

<template>
  <image
    src="https://slwl-api.itheima.net/driver/register/captcha?key=69549f14-554d-4523-a5ad-389deafc7a6b"
    mode=""
  ></image>
  <uni-forms
    class="login-form"
    :rules="accountRules"
    ref="accountForm"
    :model="formData"
  >
    <uni-forms-item name="account">
      <input
        type="text"
        v-model="formData.account"
        placeholder="请输入账号"
        class="uni-input-input"
        placeholder-style="color: #818181"
      />
    </uni-forms-item>
    <uni-forms-item name="password">
      <input
        type="text"
        v-model="formData.password"
        placeholder="请输入密码"
        class="uni-input-input"
        placeholder-style="color: #818181"
      />
    </uni-forms-item>
    <button class="submit-button" @click="onSubmitForm">登录</button>
  </uni-forms>
</template>

<style lang="scss" scoped>
  @import './styles.scss';
</style>
